package com.zgy.container_docker.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zgy.container_docker.model.Task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.*;

/**
 * @Author: zhanggy
 * @Date: 2024/6/30 9:16
 * @email: 442391947@qq.com
 * @Desc:
 */
@RequestMapping(value = "task")
@RestController
@Slf4j
public class TaskController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping(value = "list")
    public List<Task> list() {
        final Set<Object> taskKeys = redisTemplate.opsForZSet().range("tasks", 0, -1);
        log.info("taskKyes: {}", taskKeys);
        List<Task> taskList = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        assert taskKeys != null;
        taskKeys.forEach(taskId -> {
            final Map<Object, Object> entries = redisTemplate.opsForHash().entries("task:" + taskId);
            final Task task = objectMapper.convertValue(entries, Task.class);
            taskList.add(task);
        });
        return taskList;
    }

    @PostMapping(value = "add")
    public Task add(@RequestBody Task add) {
        add.setCreateTime(Instant.now().toEpochMilli());
        add.setId(UUID.randomUUID().toString());
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> map = objectMapper
                .convertValue(add, new TypeReference<>() {
                });
        redisTemplate.opsForHash().putAll("task:" + add.getId(), map);
        redisTemplate.opsForZSet().add("tasks", add.getId(), add.getCreateTime());

        return add;
    }

    @GetMapping(value = "find/{id}")
    public Object findById(@PathVariable String id) {
        final Boolean b = redisTemplate.hasKey("task:" + id);
        final Map<Object, Object> entries = redisTemplate.opsForHash().entries("task:" + id);
        return entries;
    }

    @DeleteMapping(value = "delete/{id}")
    public void delete(@PathVariable String id) {
        redisTemplate.delete("task:" + id);
        redisTemplate.opsForZSet().remove("tasks", id);
    }
}
